package common.util;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import common.bean.ResultJsonWrap;
import common.constant.GlobalConstant;

/**
 * 文件上传的工具类
 * 
 * @author liuxj
 * @version 1.0.0 2015年08月12日
 */
public class FileUploadUtils {
    private static Logger logger = Logger.getLogger(FileUploadUtils.class);

    /***
     * 
     * @param multipartFile
     * @return
     */
    public static boolean checkImage(MultipartFile multipartFile) {
    	if (multipartFile != null && !multipartFile.isEmpty()) {
    		String fileName = multipartFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
            	String postfix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if(GlobalConstant.IMAGE_TYPE_LIST.contains(postfix)) {
            		return true;
            	}
            }
    	}
    	
    	return false;
    }
    
	/**
     * 通用文件上传，创建当天的日期目录，并且使用UUID重命名文件名
     * 
     * @param multipartFile
     *            上传的文件
     * @param modeName
     *            所属模块名称
     * @return 结果数据
     */
    public static ResultJsonWrap fileUpload(HttpServletRequest request, MultipartFile multipartFile, String modeName) {
        return fileUpload(request, multipartFile, modeName, true, true);
    }

    /**
     * 通用文件上传
     * 
     * @param multipartFile
     *            上传的文件
     * @param modeName
     *            所属模块名称
     * @param createDateDir
     *            是否创建当天的日期目录
     * @param rename
     *            是否使用UUID重命名文件名
     * @return 结果数据
     */
    public static ResultJsonWrap fileUpload(HttpServletRequest request, MultipartFile multipartFile, String modeName, boolean createDateDir,
            boolean rename) {
        ResultJsonWrap result = new ResultJsonWrap();

        if (multipartFile != null && !multipartFile.isEmpty()) {
            String today = DateUtils.dateToStr(new Date(), "yyyyMMdd");

            StringBuffer dirBuf = new StringBuffer();
//            dirBuf.append(GlobalConstant.FILE_UPLOAD_DIR);
            dirBuf.append(File.separator);
            dirBuf.append(modeName);
            dirBuf.append(File.separator);
            if (createDateDir) {
                dirBuf.append(today);
            }

            String fileDir = dirBuf.toString();
            String realPath = ParamsMapUtils.getString("uploadUrl");//request.getSession().getServletContext().getRealPath("/");

            File dirFile = new File(realPath + fileDir);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }

            String fileName = multipartFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName)) {
                String postfix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String saveName = null;
                if (rename) {
                    saveName = UUID.randomUUID().toString().replaceAll("-", "") + postfix;
                } else {
                    saveName = fileName;
                }

                realPath = realPath + fileDir + File.separator + saveName;
                String relativePath = fileDir + File.separator + saveName;
                relativePath = relativePath.replaceAll("\\\\", "/");

                try {
                    multipartFile.transferTo(new File(realPath));
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    result.setErrorMsg("文件上传失败！");

                    return result;
                }

                Map<String, String> data = new HashMap<String, String>();
                data.put("fileName", fileName);
                data.put("realPath", realPath);
                data.put("relativePath", relativePath);

                result.setFlag(true);
                result.setData(data);
                result.setMsg("文件上传成功！");
            } else {
                result.setErrorMsg("文件名不能为空！");
            }
        } else {
            result.setErrorMsg("文件不存在或为空！");
        }

        return result;
    }

}
